<template>
  <div class="student-page">
    <div class="header">
      <h2>学生课程</h2>
      <el-tag type="info" v-if="studentName">学生：{{ studentName }}</el-tag>
    </div>
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="query" size="small">
        <el-form-item label="课程名">
          <el-input v-model="query.courseName" placeholder="输入课程名" clearable />
        </el-form-item>
        <el-form-item label="教师">
          <el-input v-model="query.teacherName" placeholder="输入教师名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-table :data="list" v-loading="loading" stripe style="width:100%;margin-top:12px;">
      <el-table-column prop="id" label="选课Id" width="80" />
      <el-table-column prop="courseName" label="课程名" />
      <el-table-column prop="teacherName" label="教师" width="120" />
      <el-table-column prop="credit" label="学分" width="80" />
      <el-table-column prop="dailyScore" label="日常成绩" width="100">
        <template slot-scope="s">{{ s.row.dailyScore ?? '-' }}</template>
      </el-table-column>
      <el-table-column prop="examScore" label="考试成绩" width="100">
        <template slot-scope="s">{{ s.row.examScore ?? '-' }}</template>
      </el-table-column>
      <el-table-column prop="score" label="总成绩" width="100">
        <template slot-scope="s">{{ s.row.score ?? '-' }}</template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-popconfirm title="确定退选该课程吗？" @confirm="dropSelection(scope.row)">
            <el-button size="mini" type="danger" slot="reference">退选</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="total, prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="page"
        @current-change="fetchData" />
    </div>
  </div>
</template>
<script>
import { getStudentCourseList, studentDropCourse } from '@/api'
export default {
  name:'StudentCoursesView',
  data() { return {
    studentName: '',
    list: [],
    loading: false,
    page: 1,
    pageSize: 10,
    total: 0,
    query: { courseName:'', teacherName:'' }
  }},
  created() {
    const info = this.$store.state.user.userInfo || JSON.parse(localStorage.getItem('userInfo')||'{}')
    this.studentName = info.username || info.name || ''
    if (this.$store.state.user.userType !== 1) {
      this.$message.warning('当前不是学生身份，已跳转首页')
      this.$router.replace('/home')
      return
    }
    this.fetchData()
  },
  methods: {
    async fetchData() {
      if (!this.studentName) return
      this.loading = true
      try {
        const res = await getStudentCourseList()
        let list = res.data || []
        // 统一选课记录与课程字段，方便退选与展示
        list = list.map(r => {
          const selectionId = r.id || r.selectionId || r.studentCourseId || r.scId || r.recordId
          const courseId = r.courseId || (r.course && r.course.id) || r.cid || r.id
          const courseName = r.courseName || (r.course && r.course.name) || r.name
          return { ...r, id: selectionId, selectionId, courseId, courseName }
        })
        if (process.env.NODE_ENV !== 'production') {
          console.debug('[StudentCourses][Normalized]', JSON.parse(JSON.stringify(list.slice(0,5))))
        }
        // 前端过滤（因为自助接口不支持分页与搜索）
        if (this.query.courseName) list = list.filter(i => (i.courseName||'').includes(this.query.courseName))
        if (this.query.teacherName) list = list.filter(i => (i.teacherName||'').includes(this.query.teacherName))
        this.total = list.length
        // 简单分页（前端）
        const start = (this.page - 1) * this.pageSize
        this.list = list.slice(start, start + this.pageSize)
      } catch(e) { console.error(e); this.$message.error('加载课程失败') }
      finally { this.loading = false }
    },
    search() {
      this.page = 1
      this.fetchData()
    },
    reset() {
      this.query = { courseName:'', teacherName:'' }
      this.search()
    },
    async dropSelection(row) {
      try {
        const candidates = [
          row.selectionId,
          row.id,
          row.studentCourseId,
          row.scId,
          row.recordId,
          row.courseSelectionId,
          row.courseId
        ].filter(v => v != null && v !== '' && v !== 'undefined')
        if (!candidates.length) {
          this.$message.error('无法识别选课记录ID，退选失败')
          if (process.env.NODE_ENV !== 'production') console.debug('[StudentCourses][Drop][ROW]', JSON.parse(JSON.stringify(row)))
          return
        }
        let success = false
        for (const cid of candidates) {
          try {
            if (process.env.NODE_ENV !== 'production') console.debug('[StudentCourses][Drop][TRY]', cid)
            await studentDropCourse(cid)
            success = true
            break
          } catch (e) {
            if (process.env.NODE_ENV !== 'production') console.debug('[StudentCourses][Drop][FAIL]', cid, e?.response?.data)
          }
        }
        if (!success) {
          this.$message.error('退选失败：ID均无效')
          return
        }
        this.$message.success('退选成功')
        this.fetchData()
      } catch (e) {
        this.$message.error('退选失败')
      }
    }
  }
}
</script>
<style scoped>
.student-page { padding:16px; }
.header { display:flex; gap:16px; align-items:center; }
.filter-card { margin-top:8px; }
.pagination-wrapper { margin-top:12px; text-align:right; }
</style>
